<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件管理</title>
    <style>
        body { font-family: 'Arial', sans-serif; max-width: 1200px; margin: 0 auto; padding: 20px; background-color: #f5f5f5; }
        .header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px; }
        .logo { font-size: 24px; font-weight: bold; color: #333; }
        .user-info { display: flex; align-items: center; gap: 15px; }
        .btn { padding: 8px 16px; border: none; border-radius: 4px; cursor: pointer; font-size: 14px; }
        .btn-primary { background-color: #007bff; color: white; }
        .btn-danger { background-color: #dc3545; color: white; }
        .file-actions { display: flex; gap: 10px; margin-bottom: 20px; }
        .upload-container { display: none; margin-bottom: 20px; padding: 20px; background-color: white; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
        .directory-container { margin-bottom: 20px; }
        .directory-path { font-size: 16px; margin-bottom: 10px; color: #666; }
        .file-table { width: 100%; border-collapse: collapse; background-color: white; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
        .file-table th, .file-table td { padding: 12px 15px; text-align: left; }
        .file-table th { background-color: #f8f9fa; border-bottom: 1px solid #dee2e6; }
        .file-table tr:hover { background-color: #f8f9fa; }
        .file-icon { margin-right: 8px; }
        .action-btn { margin-right: 5px; padding: 4px 8px; font-size: 12px; }
        .modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5); justify-content: center; align-items: center; }
        .modal-content { background-color: white; padding: 20px; border-radius: 8px; width: 400px; }
        .modal-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; }
        .close-btn { cursor: pointer; font-size: 20px; }
        .form-group { margin-bottom: 15px; }
        .form-control { width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; }
    </style>
</head>
<body>
    <div class="header">
        <div class="logo">文件管理系统</div>
        <div class="user-info">
            <span id="username"></span>
            <button id="logoutBtn" class="btn btn-danger">退出登录</button>
        </div>
    </div>

    <div class="file-actions">
        <button id="uploadBtn" class="btn btn-primary">上传文件</button>
        <button id="createDirBtn" class="btn btn-primary">新建目录</button>
    </div>

    <div id="uploadContainer" class="upload-container">
        <h3>上传文件</h3>
        <input type="file" id="fileInput" multiple>
        <button id="confirmUploadBtn" class="btn btn-primary">确认上传</button>
        <button id="cancelUploadBtn" class="btn">取消</button>
    </div>

    <div class="directory-container">
        <div class="directory-path" id="directoryPath">/</div>
    </div>

    <table class="file-table">
        <thead>
            <tr>
                <th>名称</th>
                <th>大小</th>
                <th>修改日期</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody id="fileTableBody">
            <!-- 文件列表将通过JavaScript动态生成 -->
        </tbody>
    </table>

    <!-- 新建目录模态框 -->
    <div id="createDirModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>新建目录</h3>
                <span class="close-btn">&times;</span>
            </div>
            <div class="form-group">
                <input type="text" id="dirNameInput" class="form-control" placeholder="请输入目录名称">
            </div>
            <button id="confirmCreateDirBtn" class="btn btn-primary">创建</button>
        </div>
    </div>

    <script>
        // 页面加载时检查登录状态
        document.addEventListener('DOMContentLoaded', function() {
            const token = localStorage.getItem('token');
            if (!token) {
                window.location.href = '/login';
                return;
            }

            // 获取用户名并显示
            const username = localStorage.getItem('username');
            document.getElementById('username').textContent = username || '用户';

            // 加载文件列表
            loadFileList();

            // 绑定事件处理函数
            bindEvents();
        });

        // 绑定所有事件处理函数
        function bindEvents() {
            // 退出登录
            document.getElementById('logoutBtn').addEventListener('click', function() {
                localStorage.removeItem('token');
                localStorage.removeItem('username');
                window.location.href = '/login';
            });

            // 上传文件按钮
            document.getElementById('uploadBtn').addEventListener('click', function() {
                document.getElementById('uploadContainer').style.display = 'block';
            });

            // 取消上传
            document.getElementById('cancelUploadBtn').addEventListener('click', function() {
                document.getElementById('uploadContainer').style.display = 'none';
                document.getElementById('fileInput').value = '';
            });

            // 确认上传
            document.getElementById('confirmUploadBtn').addEventListener('click', uploadFiles);

            // 新建目录按钮
            document.getElementById('createDirBtn').addEventListener('click', function() {
                document.getElementById('createDirModal').style.display = 'flex';
                document.getElementById('dirNameInput').value = '';
            });

            // 关闭模态框
            document.querySelector('.close-btn').addEventListener('click', function() {
                document.getElementById('createDirModal').style.display = 'none';
            });

            // 确认创建目录
            document.getElementById('confirmCreateDirBtn').addEventListener('click', createDirectory);
        }

        // 加载文件列表
        function loadFileList() {
            const token = localStorage.getItem('token');
            fetch('/api/directories/detail?path=/', {
                method: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + token,
                    'Content-Type': 'application/json'
                }
            })
            .then(response => {
                if (!response.ok) throw new Error('获取文件列表失败');
                return response.json();
            })
            .then(data => {
                console.log(data);
                if (data.code === 200) {
                    renderFileList(data.data.directories, data.data.files);
                } else {
                    alert(data.msg || '获取文件列表失败');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('获取文件列表失败，请重试');
            });
        }

        // 渲染文件列表
        function renderFileList(directories, files) {
            const tableBody = document.getElementById('fileTableBody');
            tableBody.innerHTML = '';

            // 渲染目录
            directories.forEach(dir => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td><span class="file-icon">📁</span>${dir.name}</td>
                    <td>-</td>
                    <td>${formatDate(dir.updated_at)}</td>
                    <td>
                        <button class="btn action-btn" onclick="enterDirectory('${dir.name}')">进入</button>
                        <button class="btn action-btn" onclick="renameItem('directory', '${dir.id}', '${dir.name}')">重命名</button>
                        <button class="btn action-btn btn-danger" onclick="deleteItem('directory', '${dir.id}', '${dir.name}')">删除</button>
                    </td>
                `;
                tableBody.appendChild(row);
            });

            // 渲染文件
            files.forEach(file => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td><span class="file-icon">📄</span>${file.name}</td>
                    <td>${formatFileSize(file.size)}</td>
                    <td>${formatDate(file.updated_at)}</td>
                    <td>
                        <button class="btn action-btn" onclick="downloadFile('${file.id}', '${file.name}')">下载</button>
                        <button class="btn action-btn" onclick="renameItem('file', '${file.id}', '${file.name}')">重命名</button>
                        <button class="btn action-btn btn-danger" onclick="deleteItem('file', '${file.id}', '${file.name}')">删除</button>
                    </td>
                `;
                tableBody.appendChild(row);
            });
        }

        // 上传文件
        function uploadFiles() {
            const fileInput = document.getElementById('fileInput');
            const files = fileInput.files;
            if (files.length === 0) {
                alert('请选择文件');
                return;
            }

            const formData = new FormData();
            for (let i = 0; i < files.length; i++) {
                formData.append('file', files[i]);
            }
            formData.append('directory_id', '1');

            const token = localStorage.getItem('token');
            fetch('/api/files/upload', {
                method: 'POST',
                headers: {
                    'Authorization': 'Bearer ' + token
                },
                body: formData
            })
            .then(response => {
                if (!response.ok) throw new Error('上传失败');
                return response.json();
            })
            .then(data => {
                if (data.code === 200) {
                    alert('上传成功');
                    document.getElementById('uploadContainer').style.display = 'none';
                    document.getElementById('fileInput').value = '';
                    loadFileList();
                } else {
                    alert(data.msg || '上传失败');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('上传失败，请重试');
            });
        }

        // 创建目录
        function createDirectory() {
            const dirName = document.getElementById('dirNameInput').value.trim();
            if (!dirName) {
                alert('请输入目录名称');
                return;
            }

            const token = localStorage.getItem('token');
            fetch('/api/directories/create', {
                method: 'POST',
                headers: {
                    'Authorization': 'Bearer ' + token,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    name: dirName,
                    path: '/'
                })
            })
            .then(response => {
                if (!response.ok) throw new Error('创建目录失败');
                return response.json();
            })
            .then(data => {
                if (data.code === 200) {
                    alert('目录创建成功');
                    document.getElementById('createDirModal').style.display = 'none';
                    loadFileList();
                } else {
                    alert(data.msg || '创建目录失败');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('创建目录失败，请重试');
            });
        }

        // 辅助函数：格式化日期
        function formatDate(dateString) {
            const date = new Date(dateString);
            return date.toLocaleString();
        }

        // 辅助函数：格式化文件大小
        function formatFileSize(bytes) {
            if (bytes < 1024) return bytes + ' B';
            else if (bytes < 1048576) return (bytes / 1024).toFixed(2) + ' KB';
            else return (bytes / 1048576).toFixed(2) + ' MB';
        }	

        // 以下函数需要全局作用域，供内联onclick调用
        // 进入目录
        function enterDirectory(dirName) {
            // 实际应用中需要实现目录导航逻辑
            alert('进入目录: ' + dirName);
        }

        // 重命名项目
        function renameItem(type, id, oldName) {
            const newName = prompt(`请输入新${type === 'directory' ? '目录' : '文件'}名称`, oldName);
            if (newName && newName !== oldName) {
                // 实际应用中需要实现重命名逻辑
                alert(`重命名${type === 'directory' ? '目录' : '文件'}: ${oldName} -> ${newName}`);
            }
        }

        // 删除项目
        function deleteItem(type, id, name) {
            if (confirm(`确定要删除${type === 'directory' ? '目录' : '文件'}: ${name}吗？`)) {
                // 实际应用中需要实现删除逻辑
                alert(`删除${type === 'directory' ? '目录' : '文件'}: ${name}`);
            }
        }

        // 下载文件
        function downloadFile(fileId, fileName) {
            const token = localStorage.getItem('token');
            window.location.href = `/api/files/download/${fileId}?token=${token}`;
        }
    </script>
</body>
</html>